package aooO.crm.Controller;

import aooO.crm.Service.ActivityRemarkService;
import aooO.crm.Service.ActivityService;
import aooO.crm.Service.UserService;
import aooO.crm.common.Utils.DateUtils;
import aooO.crm.common.Utils.HSSFUtils;
import aooO.crm.common.Utils.OutputUtils;
import aooO.crm.common.Utils.UUIDUtils;
import aooO.crm.mapper.ActivityRemarkMapper;
import aooO.crm.pojo.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("workbench/activity")
public class activityController {

    @Autowired
    UserService userService;
    @Autowired
    ActivityService activityService;
    @Autowired
    ActivityRemarkService activityRemarkService;

    @RequestMapping("/index.do")
    public String index(HttpServletRequest request){
        //显示页面之前把user相关的信息以及市场活动信息查出来
        List<User> userList = userService.selectAllUser();
        //存到request域方便存取
        request.setAttribute("userList",userList);
        return "workbench/activity/index";
    }


    @RequestMapping("/saveCreateActivity.do")
    @ResponseBody
    public Object saveCreateActivity(Activity activity, HttpSession session){
        /**
         * owner:owner,
         * name:name,
         * startDate:startDate,
         * endDate:endDate,
         * cost:cost,
         * description:description
         */

//        id, owner, name, start_date,
//                end_date, cost, description,
//                create_time, create_by
        activity.setId(UUIDUtils.uuid());
        activity.setCreateTime(DateUtils.FormatDateTime(new Date()));
        //从session里面获得当前登录的用户
        User user = (User) session.getAttribute(stateCode.SESSION_USER);
        activity.setCreateBy(user.getId());     //获得的是创建者的id
        returnObject msg=new returnObject();
        try{
            int i = activityService.insert(activity);
            if (i>0){
                //插入成功
                msg.setCode(stateCode.STATE_SUCCESS);
            }else {
                msg.setCode(stateCode.STATE_FAILURE);
                msg.setMessage("保存失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();

            msg.setCode(stateCode.STATE_FAILURE);
            msg.setMessage("保存失败，请重试！");
        }


        //返回是否保存成功的响应信息

        return msg;
    }

    /**
     * name:name,
     * owner:owner,
     * startDate:startDate,
     * endDate:endDate,
     * pageNo:pageNo,
     * pageSize:pageSize
     * @return
     */
    @RequestMapping("/queryActivityByConditionForPage.do")
    @ResponseBody
    public Object queryActivityByConditionForPage(String name,String owner,String startDate,String endDate,Integer pageNo,Integer pageSize){
         //封装到map中
        HashMap<String,Object> map=new HashMap<>();
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("pageStart",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        //市场活动列表
        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
//        data.totalRows
        int totalRows=activityService.selectAllCount(map);
        HashMap<String,Object> map1=new HashMap<>();
        map1.put("activityList",activityList);
        map1.put("totalRows",totalRows);
        return map1;
    }

//    workbench/activity/deleteActivityByIds.do
    @RequestMapping("/deleteActivityByIds.do")
    @ResponseBody
    public Object deleteActivityByIds(String[] id){
        //返回删除是否成功
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"");
        try{

            int i = activityService.deleteActivityByIds(id);
            if (i>0){
                //删除成功
                msg.setCode(stateCode.STATE_SUCCESS);
            }else {
                msg.setCode(stateCode.STATE_FAILURE);
                msg.setMessage("删除失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();

            msg.setCode(stateCode.STATE_FAILURE);
            msg.setMessage("删除失败，请重试！");
        }
        return msg;
    }

//    workbench/activity/queryActivityById.do
    @RequestMapping("/queryActivityById.do")
    @ResponseBody
    public Object queryActivityById(String id){
        Activity activity = activityService.queryActivityById(id);
        return activity;
    }



//    workbench/activity/saveEditActivity.do
    @RequestMapping("/saveEditActivity.do")
    @ResponseBody
    public Object saveEditActivity(Activity activity, HttpSession session){
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"");
        //从会话域中获取修改者的id
        User user = (User) session.getAttribute(stateCode.SESSION_USER);
        activity.setEditBy(user.getId());
        activity.setEditTime(DateUtils.FormatDateTime(new Date()));
        try{
            int i = activityService.saveEditActivity(activity);
            if (i>0){
                //插入成功
                msg.setCode(stateCode.STATE_SUCCESS);
            }else {
                msg.setCode(stateCode.STATE_FAILURE);
                msg.setMessage("更新失败，请重试！");
            }
        }catch (Exception e){
            e.printStackTrace();

            msg.setCode(stateCode.STATE_FAILURE);
            msg.setMessage("更新失败，请重试！");
        }
        msg.setObject(activity);
        return msg;
    }


//    workbench/activity/exportAllActivity.do  批量导出全部
    @RequestMapping("/exportAllActivity.do")
    public void exportAllActivity(HttpServletResponse response) throws IOException {
        List<Activity> activityList = activityService.selectAllActivities();
        HSSFWorkbook wb = OutputUtils.outputActivityList(activityList);
        //设置响应类型   为字节流文件
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=activities.xls");
        ServletOutputStream outputStream = response.getOutputStream();    //由于同步请求响应信息无法显示，不用捕获异常
        wb.write(outputStream);      //直接将文件写到输出流
        wb.close();
        outputStream.flush();     //冲一下输出流
    }

//    workbench/activity/exportCheckedActivity.do   批量导出某些
    @RequestMapping("/exportCheckedActivity.do")
    public void exportCheckedActivity(String[] id,HttpServletResponse response) throws IOException {
        List<Activity> activityList = activityService.selectActivitiesByIds(id);
        HSSFWorkbook wb = OutputUtils.outputActivityList(activityList);
        //设置响应类型   为字节流文件
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=activities.xls");
        ServletOutputStream outputStream = response.getOutputStream();    //由于同步请求响应信息无法显示，不用捕获异常
        wb.write(outputStream);      //直接将文件写到输出流
        wb.close();
        outputStream.flush();     //冲一下输出流
    }

//    workbench/activity/importActivity.do   导入
    @RequestMapping("/importActivity.do")
    @ResponseBody
    public Object importActivity(MultipartFile activityFile,HttpSession session){
        List<Activity> activityList=new ArrayList<>();
        User user =(User) session.getAttribute(stateCode.SESSION_USER);
        returnObject msg=new returnObject(stateCode.STATE_FAILURE,"");
        try {
            InputStream inputStream = activityFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(inputStream);    //将文件转为wb对象
            //开始逐行逐列转换
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row=null;
            HSSFCell cell=null;
            Activity activity=null;
            for (int i=1;i<sheet.getPhysicalNumberOfRows();i++){
                activity=new Activity();
                activity.setId(UUIDUtils.uuid());
                activity.setOwner(user.getId());
                activity.setCreateTime(DateUtils.FormatDateTime(new Date()));
                activity.setCreateBy(user.getId());
                row=sheet.getRow(i);   //获得行
                for(int j=0;j<row.getPhysicalNumberOfCells();j++){
                    cell=row.getCell(j);
                    if (j==0){
                        activity.setName(HSSFUtils.getValue(cell));
                    }else if (j==1){
                        activity.setStartDate(HSSFUtils.getValue(cell));
                    }else if(j==2){
                        activity.setEndDate(HSSFUtils.getValue(cell));
                    }else if (j==3){
                        activity.setCost(HSSFUtils.getValue(cell));
                    }else if (j==4){
                        activity.setDescription(HSSFUtils.getValue(cell));
                    }
                }
                activityList.add(activity);
            }

            //准备好插入的集合
            int count= activityService.insertByList(activityList);
            if (count>0){
                msg.setCode(stateCode.STATE_SUCCESS);
                msg.setReturnData(count);
            }else {
                msg.setMessage("插入失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();

            msg.setMessage("插入失败！");
        }
        return msg;
    }


    //    workbench/activity/detailActivity.do
    @RequestMapping("/detailActivity.do")
    public Object detailActivity(String id,HttpServletRequest request){
        //根据id查详情
        //传入的是activity的id   根据id查activity详情 查名下的remark
        Activity activity = activityService.selectActivityDetailById(id);
        List<ActivityRemark> activityRemarkList = activityRemarkService.selectByActivityId(id);
        //返回到详情页
        //请求转发，在request域中携带数据
        request.setAttribute("activity",activity);
        request.setAttribute("activityRemarkList",activityRemarkList);
        return "workbench/activity/detail";
    }

}

